package com.example.service.impl;

import com.example.entity.ProductType;
import com.example.entity.Result;
import com.example.mapper.ProductTypeMapper;
import com.example.service.ProductTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@CacheConfig(cacheNames = "com.example.service.impl.ProductTypeServiceImpl")
@Service
public class ProductTypeServiceImpl implements ProductTypeService {
    @Autowired
    private ProductTypeMapper productTypeMapper;
    @Cacheable(key = "'productTypeTree:all'")
    @Override
    public List<ProductType> allProductTypeToTree() {
        // 查询所有的商品分类
        List<ProductType> allPTList = productTypeMapper.selectAllProductType();

        // 对所有的商品分类进行树形化 parentId为0
        List<ProductType> productTypeTree = this.productTypeListToTree(allPTList, 0);

        // 返回结果
        return productTypeTree;
    }

    /**
     * 验证typeCode是否已经存在的业务方法
     * @param typeCode
     * @return
     */
    @Override
    public Result verifyProductTypeCode(String typeCode) {
        // 根据商品分类编码查询商品分类是否存在
        ProductType productType = productTypeMapper.selectProductTypeByTypeCode(typeCode);
        if (productType == null){ // 不存在
            return Result.ok();
        }
        // 存在
        return Result.err(Result.CODE_ERR_BUSINESS, "分类编码已存在da！");
    }

    /**
     * 把商品分类集合转为商品分类树的方法
     * @param allProductTypeList
     * @return
     */
    private List<ProductType> productTypeListToTree(List<ProductType> allProductTypeList, int parentId){
        // 存储parentId与参数parentId相等的PT对象
        List<ProductType> parentPTList = new ArrayList<>();

        // 查找parentId与参数parentId相等的PT对象
        for (ProductType productType : allProductTypeList) {
            if (parentId == productType.getParentId()){
                parentPTList.add(productType);
            }
        }

        // 以当前PT对象的id作为参数(parentId)，寻找集合中parentId与当前对象id相等的PT对象
        for (ProductType productType : parentPTList) {
            List<ProductType> childProductTypeList = productTypeListToTree(allProductTypeList, productType.getTypeId());
            productType.setChildProductCategory(childProductTypeList);
        }
        // 返回结果，是商品分类树
        return parentPTList;
    }
}
